package com.tom.jmgd.controller;

import com.alibaba.fastjson.JSONObject;
import com.tom.jmgd.config.Sign;
import com.tom.jmgd.config.WechatConfig;
import com.tom.jmgd.core.entity.ResultEntity;
import com.tom.jmgd.core.enums.ResultEnum;
import com.tom.jmgd.dao.*;
import com.tom.jmgd.entity.param.*;
import com.tom.jmgd.service.PdService;
import com.tom.jmgd.util.HttpUtil;
import com.tom.jmgd.util.SendSms;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/pd")
public class PdController {
    @Autowired
    TPdHMapper tPdHMapper;

    @Autowired
    TPdDMapper tPdDMapper;

    @Autowired
    TBusnoMapper tBusnoMapper;

    @Autowired
    TWareFromHdMapper tWareFromHdMapper;

    @Autowired
    huobanSyncDataDao huobanSyncDataDao1;

    @Autowired
    PdService pdService;

    @Autowired
    TCheckcodeMapper tCheckcodeMapper;

    @Autowired
    TPdEmpMapper tPdEmpMapper;

    @Autowired
    TWxTokenMapper tWxTokenMapper;

    @Autowired
    TPdWareStockMapper tPdWareStockMapper;

    @RequestMapping("/qureyWareMakeno")
    public ResultEntity qureyWareMakeno(@RequestParam(value = "warecode") String warecode,
                                        @RequestParam(value = "busno") String busno,
                                        @RequestParam(value = "pdHId") Long pdHId) {
        List<TPdWareStock> tPdWareStockList = tPdWareStockMapper.selectByWarecode(warecode,busno,pdHId);
        List<String> list = new ArrayList<>();
        for(TPdWareStock tPdWareStock:tPdWareStockList){
            list.add(tPdWareStock.getMakeno());
        }
        list.add("无");
        // 使用toArray()方法
        Object[] array = list.toArray();

        return new ResultEntity(ResultEnum.SUCCESS,array);
    }

    @RequestMapping("/qureyByBusno")
    public ResultEntity qureyByBusno(@RequestParam(value = "busno") String busno) {
        List<TPdH> tPdHList = tPdHMapper.selectByBusno(busno);
        List<TPdHParam> targetList = new ArrayList<>();
        for (TPdH sourceEntity : tPdHList) {
            TPdHParam targetEntity = new TPdHParam();
            targetEntity.setPdId(sourceEntity.getPdId());
            targetEntity.setBusno(sourceEntity.getBusno());
            targetEntity.setOrgname(sourceEntity.getOrgname());
            targetEntity.setCreateDatetime(sourceEntity.getCreateDatetime());
            targetEntity.setCreateEmpname(sourceEntity.getCreateEmpname());
            if(null==sourceEntity.getType() || "Q".equals(sourceEntity.getType())){
                targetEntity.setType("按数量");
            }else if("M".equals(sourceEntity.getType())){
                targetEntity.setType("按批号");
            }
            targetList.add(targetEntity);
        }
        return new ResultEntity(ResultEnum.SUCCESS,targetList);
    }

    @RequestMapping("/qureyOrgnameByBusno")
    public ResultEntity qureyOrgnameByBusno(@RequestParam(value = "busno") String busno) {
        TBusno tBusno = tBusnoMapper.selectByBusno(busno);
        return new ResultEntity(ResultEnum.SUCCESS,tBusno);
    }

    @RequestMapping("/qureyWareFromHdByWarecode")
    public ResultEntity qureyWareFromHdByWarecode(@RequestParam(value = "warecode") String warecode) {
        TWareFromHd tWareFromHd = tWareFromHdMapper.selectByWarecode(warecode);
        return new ResultEntity(ResultEnum.SUCCESS,tWareFromHd);
    }

    @RequestMapping("/qureyWareFromHdByBarcode")
    public ResultEntity qureyWareFromHdByBarcode(@RequestParam(value = "barcode") String barcode) {
        TWareFromHd tWareFromHd = tWareFromHdMapper.selectByBarcode(barcode);
        return new ResultEntity(ResultEnum.SUCCESS,tWareFromHd);
    }

    //根据条形码查询批号
    @RequestMapping("/qureyWareMakenoFromHdByBarcode")
    public ResultEntity qureyWareMakenoFromHdByBarcode(@RequestParam(value = "barcode") String barcode,
                                                       @RequestParam(value = "busno") String busno,
                                                       @RequestParam(value = "pdHId") Long pdHId) {
        List<TPdWareStock> tPdWareStockList =tPdWareStockMapper.selectByBarcode(barcode,busno,pdHId);
        TWareFromHdMakenoParam tWareFromHdMakenoParam = new TWareFromHdMakenoParam();
        if(tPdWareStockList.size() > 0){
            TPdWareStock tPdWareStock = tPdWareStockList.get(0);
            tWareFromHdMakenoParam.setAreaname(tPdWareStock.getAreaname());
            tWareFromHdMakenoParam.setBarcode(tPdWareStock.getBarcode());
            tWareFromHdMakenoParam.setFactoryname(tPdWareStock.getFactoryname());
            tWareFromHdMakenoParam.setWarecode(tPdWareStock.getWarecode());
            tWareFromHdMakenoParam.setWarename(tPdWareStock.getWarename());
            tWareFromHdMakenoParam.setWarespec(tPdWareStock.getWarespec());
            tWareFromHdMakenoParam.setWareunit(tPdWareStock.getWareunit());
            List<TWareFromHdMakenoDParam> tWareFromHdMakenoDParamList = new ArrayList<>();
            for(TPdWareStock tPdWareStock1:tPdWareStockList){
                TWareFromHdMakenoDParam tWareFromHdMakenoDParam = new TWareFromHdMakenoDParam();
                tWareFromHdMakenoDParam.setMakeno(tPdWareStock1.getMakeno());
                tWareFromHdMakenoDParamList.add(tWareFromHdMakenoDParam);
            }
            tWareFromHdMakenoParam.settWareFromHdMakenoDParamList(tWareFromHdMakenoDParamList);
        }
        return new ResultEntity(ResultEnum.SUCCESS,tWareFromHdMakenoParam);
    }

    //根据商品编码查询批号
    @RequestMapping("/qureyWareMakenoFromHdByWarecode")
    public ResultEntity qureyWareMakenoFromHdByWarecode(@RequestParam(value = "warecode") String warecode,
                                                       @RequestParam(value = "barcode") String busno,
                                                       @RequestParam(value = "barcode") Long pdHId) {
        List<TPdWareStock> tPdWareStockList =tPdWareStockMapper.selectByWarecode(warecode,busno,pdHId);
        TWareFromHdMakenoParam tWareFromHdMakenoParam = new TWareFromHdMakenoParam();
        if(tPdWareStockList.size() > 0){
            TPdWareStock tPdWareStock = tPdWareStockList.get(0);
            tWareFromHdMakenoParam.setAreaname(tPdWareStock.getAreaname());
            tWareFromHdMakenoParam.setBarcode(tPdWareStock.getBarcode());
            tWareFromHdMakenoParam.setFactoryname(tPdWareStock.getFactoryname());
            tWareFromHdMakenoParam.setWarecode(tPdWareStock.getWarecode());
            tWareFromHdMakenoParam.setWarename(tPdWareStock.getWarename());
            tWareFromHdMakenoParam.setWarespec(tPdWareStock.getWarespec());
            tWareFromHdMakenoParam.setWareunit(tPdWareStock.getWareunit());
            List<TWareFromHdMakenoDParam> tWareFromHdMakenoDParamList = new ArrayList<>();
            for(TPdWareStock tPdWareStock1:tPdWareStockList){
                TWareFromHdMakenoDParam tWareFromHdMakenoDParam = new TWareFromHdMakenoDParam();
                tWareFromHdMakenoDParam.setMakeno(tPdWareStock1.getMakeno());
                tWareFromHdMakenoDParamList.add(tWareFromHdMakenoDParam);
            }
            tWareFromHdMakenoParam.settWareFromHdMakenoDParamList(tWareFromHdMakenoDParamList);
        }
        return new ResultEntity(ResultEnum.SUCCESS,tWareFromHdMakenoParam);
    }

    @PostMapping("/pddCreate")
    public ResultEntity pddCreate(@RequestBody TPdD tPdD) {
        tPdD.setCreateDatetime(LocalDateTime.now());
        tPdDMapper.insert(tPdD);
        return new ResultEntity(ResultEnum.SUCCESS,null);
    }

    @PostMapping("/pdhCreate")
    public ResultEntity pdhCreate(@RequestBody TPdH tPdH) {
        pdService.pdhCreate(tPdH);
        System.out.println(LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")));
        pdService.syncPd(tPdH);
        System.out.println(LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")));
        return new ResultEntity(ResultEnum.SUCCESS,null);
    }


    @RequestMapping("/qureyPddByWarecode")
    public ResultEntity qureyPddByWarecode(@RequestParam(value = "warecode") String warecode,
                                           @RequestParam(value = "pdHid") Long pdHid) {
        List<TPdD> tPdDList = tPdDMapper.selectByWarecode(warecode,pdHid);
        List<TPdDParam> targetList = new ArrayList<>();
        for (TPdD sourceEntity : tPdDList) {
            TPdDParam targetEntity = new TPdDParam();
            targetEntity.setWarecode(sourceEntity.getWarecode());
            targetEntity.setQty(sourceEntity.getQty());
            targetEntity.setCreateEmpname(sourceEntity.getCreateEmpname());
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            targetEntity.setCreateDatetime(sourceEntity.getCreateDatetime().format(formatter));
            targetEntity.setPdDId(sourceEntity.getPdDId());
            targetList.add(targetEntity);
        }
        return new ResultEntity(ResultEnum.SUCCESS,targetList);
    }

    @RequestMapping("/qureyPddByWarecodeMakeno")
    public ResultEntity qureyPddByWarecodeMakeno(@RequestParam(value = "warecode") String warecode,
                                           @RequestParam(value = "pdHid") Long pdHid) {
        List<TPdD> tPdDList = tPdDMapper.selectByWarecode(warecode,pdHid);
        List<TPdDMakenoParam> targetList = new ArrayList<>();
        for (TPdD sourceEntity : tPdDList) {
            TPdDMakenoParam targetEntity = new TPdDMakenoParam();
            targetEntity.setWarecode(sourceEntity.getWarecode());
            targetEntity.setQty(sourceEntity.getQty());
            targetEntity.setCreateEmpname(sourceEntity.getCreateEmpname());
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            targetEntity.setCreateDatetime(sourceEntity.getCreateDatetime().format(formatter));
            targetEntity.setPdDId(sourceEntity.getPdDId());
            targetEntity.setMakeno(sourceEntity.getMakeno());
            targetList.add(targetEntity);
        }
        return new ResultEntity(ResultEnum.SUCCESS,targetList);
    }

    @RequestMapping("/qureyPddCount")
    public ResultEntity qureyPddCount(@RequestParam(value = "pdHid") Long pdHid,@RequestParam(value = "type") String type) {

        int result = 0;
        if("按批号".equals(type)){
            result = tPdWareStockMapper.selectCount(pdHid);
        }else if("按数量".equals(type)){
            result = huobanSyncDataDao1.selectPdStockKz(pdHid);
        }
        return new ResultEntity(ResultEnum.SUCCESS,result);
    }

    @RequestMapping("/updatePdd")
    public ResultEntity updatePdd(@RequestParam(value = "pdDId") Long pdDId) {
        TPdD tPdD = tPdDMapper.selectByPdDId(pdDId);
        tPdD.setStatus("D");
        tPdDMapper.updateById(tPdD);
        return new ResultEntity(ResultEnum.SUCCESS,null);
    }

    @RequestMapping( value = "/sendSMSCode")
    public ResultEntity sendSMSCode(@RequestParam(value = "mobile") String mobile) throws Exception {
        System.out.println("发送验证码"+mobile);
         TPdEmp tPdEmp =tPdEmpMapper.selectByMobile(mobile);
         if (null != tPdEmp) {

             TCheckcode tCheckcode = new TCheckcode();

             String newPw = String.valueOf((int) ((Math.random() * 9 + 1) * Math.pow(10, 5)));
             tCheckcode.setCheckcode(newPw);
             tCheckcode.setCreatedate(LocalDateTime.now());
             tCheckcode.setMobile(mobile);
             tCheckcodeMapper.insert(tCheckcode);
             SendSms.sendSms(mobile, newPw);
             return new ResultEntity(ResultEnum.SUCCESS, tPdEmp);
         }else{
             return new ResultEntity(ResultEnum.FAIL, null);
         }
    }


    @RequestMapping( value = "/checkSMSCode")
    public ResultEntity checkSMSCode(@RequestParam(value = "mobile") String mobile,
                                     @RequestParam(value = "checkcode") String checkcode) throws Exception {
        Integer result = tCheckcodeMapper.selectByMobile(mobile,checkcode);
        if(result > 0){
            return new ResultEntity(ResultEnum.SUCCESS, null);
        }else{
            return new ResultEntity(ResultEnum.FAIL, null);
        }
    }

    @RequestMapping( value = "/getTicket")
    public ResultEntity getTicket(@RequestParam(value = "url") String url) throws Exception {
        TWxToken tWxToken = tWxTokenMapper.selectValidDate();
        String jsapi_ticket = null;
        if(null!=tWxToken){
            jsapi_ticket = tWxToken.getJsapiticket();
        }else {
            String result = HttpUtil.getRequest("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx31bbd830784df0f3&secret=210654aa4ec27bc390efead48bac928e");
            String result2 = HttpUtil.getRequest("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + JSONObject.parseObject(result).getString("access_token") + "&type=jsapi");
             jsapi_ticket = JSONObject.parseObject(result2).getString("ticket");
            TWxToken tWxToken1= new TWxToken();
            tWxToken1.setAccesstoken(JSONObject.parseObject(result).getString("access_token") );
            tWxToken1.setCreatedate(LocalDateTime.now());
            tWxToken1.setJsapiticket(jsapi_ticket);
            tWxTokenMapper.deleteAll();
            tWxTokenMapper.insert(tWxToken1);
        }
        Map<String, String> map = Sign.sign(jsapi_ticket, url);
        for (Map.Entry entry : map.entrySet()) {
            System.out.println(entry.getKey() + ", " + entry.getValue());
        }
        return new ResultEntity(ResultEnum.SUCCESS, map);
    }
}
